package top.infopub.mgr.mkt.web;


import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import top.infopub.dto.mkt.DiscloseProDto;
import top.infopub.enums.mkt.ProProcesssStatusEnum;
import top.infopub.mgr.common.page.ParamPage;
import top.infopub.mgr.common.vo.RspVo;
import top.infopub.mgr.flow.web.GenericFlowController;
import top.infopub.mgr.hr.service.StaffInfoService;
import top.infopub.mgr.mkt.domain.DiscloseProDomain;
import top.infopub.mgr.mkt.jsonvo.DiscloseProJsonVo;
import top.infopub.mgr.mkt.service.DeciProService;
import top.infopub.mgr.mkt.service.DiscloseProAttService;
import top.infopub.mgr.mkt.service.DiscloseProService;
import top.infopub.mgr.mkt.service.ProProcessManageService;
import top.infopub.mgr.mkt.vo.DiscloseProVo;
import top.infopub.mgr.sg.service.CoopInfoService;
import top.infopub.model.mkt.DisclosePro;
import top.infopub.model.mkt.ProjectAttachment;
import top.infopub.security.util.SessionUserUtils;
import top.infopub.security.vo.AuthorizationVO;
import top.infopub.tdp.sys.service.CodeGeneratorConfigService;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;


/**
 * 交底管理
 * @author wangw
 * @version 2020年1月10日
 * @see DiscloseProjectController
 * @since
 */
@Controller
@RequestMapping("/disclosePro")
public class DiscloseProjectController extends GenericFlowController {

    @Autowired
    private DiscloseProService discloseProService;
    
    @Autowired
    private DeciProService deciProService;
    
    @Autowired
    private DiscloseProAttService discloseProAttService;
    
    @Autowired
    private StaffInfoService staffInfoService;
    
    @Autowired
    private CoopInfoService coopInfoService;
    
    @Autowired
    private CodeGeneratorConfigService codeGeneratorConfigService;

    @Autowired
    private ProProcessManageService proProcessManageService;

    /**
     * 交底列表
     * @return
     */
    @RequestMapping("/list")
    public String list() {
        return "mkt/lay-disclosePro-list";
    }
    
    /**
     * 交底列表数据
     * @return
     */
    @RequestMapping("/queryDataByCondition")
    @ResponseBody
    public RspVo<DiscloseProDomain> queryDataByCondition(DiscloseProVo discloseProVo, ParamPage paramPage) throws ParseException {
        Page<DiscloseProDomain> page = new Page<DiscloseProDomain>();
        page.setPageNum(paramPage.getPage());
        page.setPageSize(paramPage.getLimit());
        //查询时，结束日期增加一天
//        if (discloseProVo.getEndDate() != null) {
//            discloseProVo.setEndDate(DateUtils.addDays(discloseProVo.getEndDate(), 1));
//        }
        //查询时，投标截止日结束日期增加一天
//        if (discloseProVo.getDiscloseEndDate() != null) {
//            discloseProVo.setDiscloseEndDate(DateUtils.addDays(discloseProVo.getDiscloseEndDate(), 1));
//        }
        page = discloseProService.selectPageByDomainWhere(page, discloseProVo);
        return RspVo.getSuccessResponse(page.getTotal(), page.getResult());
    }
    
    /**
     * 交底-我审批的列表数据
     * @return
     */
//    @RequestMapping("/queryMyCheckDataByCondition")
//    @ResponseBody
//    public RspVo<DiscloseProDomain> queryMyCheckDataByCondition(DiscloseProVo discloseProVo, ParamPage paramPage) {
//        Page<DiscloseProDomain> page = new Page<DiscloseProDomain>();
//        page.setPageNum(paramPage.getPage());
//        page.setPageSize(paramPage.getLimit());
//        //查询时，结束日期增加一天
//        if (discloseProVo.getEndDate() != null) {
//            discloseProVo.setEndDate(DateUtils.addDays(discloseProVo.getEndDate(), 1));
//        }
//        //查询时，投标截止日结束日期增加一天
////        if (discloseProVo.getDiscloseEndDate() != null) {
////            discloseProVo.setDiscloseEndDate(DateUtils.addDays(discloseProVo.getDiscloseEndDate(), 1));
////        }
//        discloseProVo.setAddBy(SessionUserUtils.getSessionUserId());
//        page = discloseProService.selectMyCheckByDomainWhere(page, discloseProVo);
//        return RspVo.getSuccessResponse(page.getTotal(), page.getResult());
//    }
//
    /**
     * 交底-新增
     * @return
     */
//    @RequestMapping("/add")
//    public String add(HttpServletRequest request) {
//        //查询可交底的记录
//        List<DeciPro> deciPros = deciProService.selectUsableDeciPro();
//        request.setAttribute("deciPros", deciPros);
//        return "mkt/lay-disclosePro-add";
//    }
    
    /**
     * 根据id查询交底详情  > 注意：方法命名必须为：toDealOrDetail
     * @param id 交底Id
     * @return
     * @see
     */
//    @RequestMapping("/toDealOrDetail")
//    public ModelAndView queryById(HttpServletRequest request,String id, String processDealWith){
//        Map<String, Object> map = new HashMap<String, Object>();
//        DiscloseProVo disclosePro = discloseProService.selectById(id);
//        map.put("disclosePro", disclosePro);
//        // 审批flag
//        request.setAttribute("processDealWith", processDealWith);
//        // 审批data
//        processData(request, disclosePro.getProcessId());
//        return new ModelAndView("mkt/lay-disclosePro-detail", map);
//    }

    @RequestMapping("/toDealOrDetail")
    public String queryById(HttpServletRequest request, String id, String proCode){
        AuthorizationVO vo = SessionUserUtils.getSessionAttributeForUserDtl();
        request.setAttribute("id", id);
        DisclosePro disPro = discloseProService.selectByPrimaryKey(id);
        request.setAttribute("isAuditFlag", "1");
        request.setAttribute("auditTabFlag", "0");
        if (disPro != null) {
            if (StringUtils.equals(ProProcesssStatusEnum.PRO_STATUS1.getCode(), disPro.getProcessStatus())
                    || StringUtils.equals(ProProcesssStatusEnum.PRO_STATUS9.getCode(), disPro.getProcessStatus())) {
                request.setAttribute("isAuditFlag", "0");
            }
            if (StringUtils.isNotBlank(disPro.getProcessId()) && disPro.getProcessId().length() > 10) {
                request.setAttribute("processId", disPro.getProcessId());
                String auditTabFlag = proProcessManageService.checkShowAuditTab(disPro.getProcessId(), vo);
                if (StringUtils.equals(ProProcesssStatusEnum.PRO_STATUS1.getCode(), disPro.getProcessStatus())
                        && StringUtils.equals("0", auditTabFlag)) {
                    request.setAttribute("isAuditFlag", "0");
                }
                request.setAttribute("auditTabFlag", auditTabFlag);
            }
        }
        request.setAttribute("proCode", proCode);
        return "mkt/lay-confess-detail";
    }

    @RequestMapping("/queryDetailById")
    @ResponseBody
    public RspVo queryDetailById(String id) {
        //交底详情
        DiscloseProJsonVo disProJson = discloseProService.queryDetailById(id);
        return RspVo.getSuccessResponse(disProJson);
    }

    @RequestMapping("/auditProcess")
    @ResponseBody
    public RspVo auditProcess(String id, String processId, String status, String auditMsg) {
        //立项审批
        proProcessManageService.auditProject(id, processId, status, auditMsg, null);
        return RspVo.getSuccessResponse();
    }
    
    /**
     * 交底-复制单据
     * @return
     */
    @RequestMapping("/toCopy")
    public String toCopy(HttpServletRequest request,String id) {
        DiscloseProVo disclosePro = discloseProService.selectById(id);
        request.setAttribute("disclosePro", disclosePro);
        return "mkt/lay-disclosePro-copy";
    }
    
    /**
     * 新增交底
     * @return
     */
//    @SuppressWarnings({"rawtypes"})
//    @RequestMapping("/save")
//    public @ResponseBody RspVo save(HttpServletRequest request,DiscloseProVo disclosePro) {
//        //判断项目是否已存在
//        List<DisclosePro> disclosePros = discloseProService.selectByProCode(disclosePro.getProCode());
//        if(CollectionUtils.isNotEmpty(disclosePros)){
//            return ErrorCodeEnum.ERROR_COMMON_SAVE.getRspVo("项目【" + disclosePro.getProName()
//                + "】已交底~");
//        }
//        String[] sgCoopId = request.getParameterValues("sgCoopId");//单位名称
//        String[] coopEffect = request.getParameterValues("coopEffect");//单位作用
//
//        String[] orderIdx = request.getParameterValues("orderIdx");//子项序号
//        String[] subName = request.getParameterValues("subName");//子项名称
//        String[] subWorkYears = request.getParameterValues("subWorkYears");//子项-合作周期（年）
//        String[] subBuildYears = request.getParameterValues("subBuildYears");//子项-建设周期（年）
//        String[] subOmYears = request.getParameterValues("subOmYears");//子项-运营周期（年）
//
//        String[] itemOrderIdx = request.getParameterValues("itemOrderIdx");//投标报价序号
//        String[] itemNames = request.getParameterValues("itemName");//条目名称
//        String[] itemPercents = request.getParameterValues("itemPercent");//所占比例
//
//        AuthorizationVO vo = SessionUserUtils.getSessionAttributeForUserDtl();
//
//        /**
//         * 交底主表处理
//         */
//        String id = IdFactory.getUUIDUpper();
//        disclosePro.setId(id);
//        disclosePro.setHrStaffApplyId(vo.getHrStaffId());
//        disclosePro.setHrOrgId(disclosePro.getDiscloseOrgId());
//        disclosePro.setHrDeptId(disclosePro.getDiscloseDeptId());
//        StaffInfo staffInfo = staffInfoService.selectByPrimaryKey(vo.getHrStaffId());
//        disclosePro.setStaffName(staffInfo.getStaffName());
//        disclosePro.setAddBy(vo.getId());
//        disclosePro.setAddTime(top.infopub.mgr.util.DateUtils.getCurrentDateTime());
//        String codes = codeGeneratorConfigService.generatorCode("mkt_disclose_pro_codes");
//        disclosePro.setCodes(codes);
//        // 处理processId
//        disclosePro.setProcessId(IdFactory.getUUIDUpper());
//        disclosePro.setProcessStatus("1");//审批中
//        disclosePro.setUptBy(vo.getId());
//        disclosePro.setUptTime(top.infopub.mgr.util.DateUtils.getCurrentDateTime());
//
//        //合作单位处理
//        List<DiscloseProCoop> discloseProCoops = new ArrayList<DiscloseProCoop>();
//        if(sgCoopId != null && sgCoopId.length > 0){
//            for(int i=0; i<sgCoopId.length; i++){
//                String coopId = sgCoopId[i];
//                String coopeffect = coopEffect[i];
//                if(StringUtils.isEmpty(coopId) && StringUtils.isEmpty(coopeffect)){
//                    continue;
//                }
//                String coopid = IdFactory.getUUIDUpper();//自动生成主键
//                DiscloseProCoop discloseProCoop = new DiscloseProCoop();
//                discloseProCoop.setId(coopid);
//                discloseProCoop.setDiscloseProId(id);
//                discloseProCoop.setSgCoopId(coopId);
//                discloseProCoop.setCoopEffect(coopeffect);
//                discloseProCoop.setAddBy(vo.getId());
//                discloseProCoop.setAddTime(top.infopub.mgr.util.DateUtils.getCurrentDateTime());
//                discloseProCoops.add(discloseProCoop);
//            }
//
//        }
//
//        //子项处理
//        List<DiscloseProSub> discloseProSubs = new ArrayList<DiscloseProSub>();
//        if(orderIdx != null){
//            for(int i=0; i<orderIdx.length; i++){
//                String orderId = orderIdx[i];
//                DiscloseProSub discloseProSub = new DiscloseProSub();
//                String subId = IdFactory.getUUIDUpper();//自动生成主键
//                discloseProSub.setId(subId);
//                discloseProSub.setDiscloseProId(id);
//                discloseProSub.setOrderIdx(Integer.parseInt(orderId));
//                discloseProSub.setSubName(subName[i]);
//                discloseProSub.setWorkYears(new BigDecimal(subWorkYears[i]));
//                discloseProSub.setBuildYears(new BigDecimal(subBuildYears[i]));
//                discloseProSub.setOmYears(new BigDecimal(subOmYears[i]));
//                discloseProSub.setAddBy(vo.getId());
//                discloseProSub.setAddTime(top.infopub.mgr.util.DateUtils.getCurrentDateTime());
//                discloseProSubs.add(discloseProSub);
//            }
//        }
//        //投标报价处理
//        List<DiscloseProQuote> discloseProQuotes = new ArrayList<DiscloseProQuote>();
//        if(itemNames != null){
//            for(int i=0; i<itemNames.length; i++){
//                if(StringUtils.isNotEmpty(itemNames[i]) && StringUtils.isNotEmpty(itemPercents[i])){
//                    String orderId = itemOrderIdx[i];
//                    DiscloseProQuote discloseProQuote = new DiscloseProQuote();
//                    String subId = IdFactory.getUUIDUpper();//自动生成主键
//                    discloseProQuote.setId(subId);
//                    discloseProQuote.setDiscloseProId(id);
//                    discloseProQuote.setOrderIdx(Integer.parseInt(orderId));
//                    discloseProQuote.setItemName(itemNames[i]);
//                    discloseProQuote.setItemPercent(new BigDecimal(itemPercents[i]));
//                    discloseProQuote.setAddBy(vo.getId());
//                    discloseProQuote.setAddTime(top.infopub.mgr.util.DateUtils.getCurrentDateTime());
//                    discloseProQuotes.add(discloseProQuote);
//                }
//            }
//        }
//        /**
//         * 查询【预立项】、【立项】、【资格预审】、【决策】所有附件
//         */
//        List<DiscloseProAtt> fileAtts = discloseProAttService.selectAllProAtts(id,vo.getId(),disclosePro.getProCode());
//
//        discloseProService.addDisclosePro(disclosePro, discloseProCoops, discloseProSubs, discloseProQuotes, fileAtts);
//        LogUtil.bizLog(LogModelType.PROJECT, AcctionType.ADD, "交底 -新增交底：项目名="+disclosePro.getProName(), null);
//        return RspVo.getSuccessResponse();
//    }
    
    /**
     * 根据id查询交底记录
     * @param id
     * @return
     * @throws Exception
     */
//    @RequestMapping("/getDiscloseProById")
//    @ResponseBody
//    public Map<String, Object> getDiscloseProById(String id) {
//        boolean flag = true;
//        Map<String, Object> map = new HashMap<String, Object>();
//        try {
//            DiscloseProVo discloseProVo = discloseProService.selectById(id);
//            AuthorizationVO authorizationVO = SessionUserUtils.getSessionAttributeForUserDtl();
//            StaffInfo staffInfo = staffInfoService.selectByPrimaryKey(authorizationVO.getHrStaffId());
//            discloseProVo.setStaffName(staffInfo.getStaffName());
//            map.put("discloseProVo", discloseProVo);
//        }
//        catch (Exception e) {
//            log.error("查询交底记录异常", e);
//            flag = false;
//        }
//        map.put("flag", flag);
//        return map;
//    }
//
    /**
     * 上传附件
     * @param request
     * @return 
     * @throws IOException 
     * @see
     */
//    @SuppressWarnings("rawtypes")
//    @RequestMapping("/uploadAtt")
//    public @ResponseBody RspVo uploadAtt(HttpServletRequest request)
//        throws IOException {
//        List<String> returnFileStrList = new ArrayList<>();
//        MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest)request;
//        Map<String, MultipartFile> map = multipartHttpServletRequest.getFileMap();
//        if (map != null) {
//            for (String name : map.keySet()) {
//                MultipartFile file = map.get(name);
//                //资料类型
//                String types = request.getParameter("types");
//                if(StringUtils.isEmpty(types)){
//                    return ErrorCodeEnum.ERROR_COMMON_PARAM.getRspVo("缺少参数");
//                }
//                if (file == null) {
//                    return ErrorCodeEnum.ERROR_COMMON_PARAM.getRspVo("上传文件不能为空");
//                }
//                // 上传文件
//                String fileId = IdFactory.getUUIDSerialNumber();
//                // 服务器资源路径
//                String serverPath = "discloseProAtt";
//                String filePath = FileHelper.upload(file, serverPath);
//                returnFileStrList.add(types+"|"+file.getOriginalFilename().trim() + "|" + fileId + "|"
//                                      + filePath);
//                LogUtil.bizLog(LogModelType.PROJECT, AcctionType.ADD, "上传附件-文件名:" + filePath
//                                                                      + "，文件路径:" + filePath, null);
//            }
//        }
//        return RspVo.getSuccessResponse(returnFileStrList);
//    }

    /**
     * 编辑投标决策
     * @param request
     * @return
     */
    @RequestMapping("/edit")
    public @ResponseBody RspVo edit(HttpServletRequest request, String bodyStr, Integer submitType) {
        AuthorizationVO vo = SessionUserUtils.getSessionAttributeForUserDtl();
        String str = StringEscapeUtils.unescapeJava(bodyStr);
        DiscloseProJsonVo disProJson = JSON.parseObject(str, DiscloseProJsonVo.class);
        DiscloseProDto disProDto = disProJson.getInfo();
        //更新交底表-MKT_DISCLOSE_PRO
        DisclosePro disPro = new DisclosePro();
        BeanUtils.copyProperties(disProDto, disPro);

        //更新附件表-MKT_PROJECT_ATTACHMENT
        List<ProjectAttachment> attachmentList = new ArrayList<>();
        if(disProJson.getFileAtt()!=null){
            String[] fileAtt = disProJson.getFileAtt();
            for (String file : fileAtt) {
                ProjectAttachment attachment = createProjectFileAtta(vo, disPro.getProCode(), file);
                attachmentList.add(attachment);
            }
        }

        //调用service进行数据库操作
        RspVo rspVo = discloseProService.editDetail(disPro, attachmentList, vo, submitType);
        return rspVo;
    }
}
